﻿using Core.Framework.Model.WebSockets;
using Core.Framework.Loger;
using Core.Service.TaskHandle;
using Core.Service.TaskHandle.Task_Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;

namespace Core.Framework.Redis.Task_Listener
{
    [Listenner(Template = "Job")]
    public class Jobs_Linstener : BaseMQMsgListener,IMQMsgListener
    {
        public DoWork_Out DoWork(MessageQueue messageQueue)
        {
            try
            {
                Func<KeyValuePair<WebSocket, ClientInfo>, bool> where = a =>
                    a.Value.User.Subscription.Contains(messageQueue.Message.MessageKey)
                    && a.Value.Project.ProjectToken == messageQueue.ClientInfo.Project.ProjectToken;

                var outModel = new DoWork_Out { OK = true, Message = messageQueue };

                var json = this.StructureParameter(messageQueue);

                switch (messageQueue.Message.MessageType)
                {
                    case MessageTypeEnum.Single:
                        var result = WebSocketApplication.ClientsPool.Where(where).OrderBy(a => a.Value.TaskLength).FirstOrDefault();
                        if (null != result.Value && result.Key != null)
                        {
                            this.SendMessage(result.Key, json);
                        }
                        else
                            outModel.Action = "SingleNull";

                        break;
                    case MessageTypeEnum.Group:
                        var results = WebSocketApplication.ClientsPool.Where(where);
                        if (results.Count() > 0)
                            foreach (var client in results)
                                this.SendMessage(client.Key, json);
                        else
                            outModel.Action = "GroupNull";

                        break;
                }

                return outModel;
            }
            catch (Exception e)
            {
                LogFactory.GetLogger(typeof(Jobs_Linstener)).Debug(e);
                return new DoWork_Out
                {
                    Message = messageQueue,
                    OK = false,
                    Parameters = new string[] { e.Message, "5000" },
                    Action = "errer"
                };
            }
        }

        public void Errer(DoWork_Out model)
        {
            
        }

        public void Success(DoWork_Out model)
        {
            
        }
    }
}
